/*
 * 日期选择框
 * name placeholder Name
 * onChange 放在FormItem 下自动传过来的方法，在Form表单里使用无需传值
 **/

import React, { useMemo } from 'react';
import { DatePicker } from 'antd';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { SchemaManageAPI } from '../../type';

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

interface IPropsType {
  id?: string;
  value?: any;
  onChange?: any;
  opt: SchemaManageAPI.ISearchList;
  type: string;
  ranges?: any;
}

const { RangePicker }: any = DatePicker;

export const SearchRangePicker: React.FC<IPropsType> = (props) => {
  /**
   * 传入的参数
   * showRange: { today: true, week: true, month: false, year: false }
   * 控制今天 本周 本月 本年 显示隐藏
   */
  const controlRange = useMemo(() => {
    let ranges: any = {};
    if (props?.opt?.showRange && JSON.stringify(props?.opt?.showRange) != '{}') {
      if (props?.opt?.showRange?.today) {
        ranges['今天'] = [moment(), moment()];
      }
      if (props?.opt?.showRange?.week) {
        ranges['本周'] = [moment().startOf('week'), moment().endOf('week')];
      }
      if (props?.opt?.showRange?.month) {
        ranges['本月'] = [moment().startOf('month'), moment().endOf('month')];
      }
      if (props?.opt?.showRange?.year) {
        ranges['本年'] = [moment().startOf('year'), moment().endOf('year')];
      }
    } else {
      ranges = {
        今天: [moment(), moment()],
        本周: [moment().startOf('week'), moment().endOf('week')],
        本月: [moment().startOf('month'), moment().endOf('month')],
        本年: [moment().startOf('year'), moment().endOf('year')],
      };
    }
    if (props?.opt?.ranges) {
      ranges = props?.opt?.ranges;
    }
    return ranges;
  }, [props?.opt?.showRange]);

  return (
    <RangePicker
      onChange={props?.onChange}
      locale={locale}
      value={props?.value ?? null}
      style={{ width: '100%' }}
      placeholder={props?.opt?.placeholder ? [`${props?.opt?.placeholder}时间范围`, `${props?.opt?.placeholder}时间范围`] : ['时间开始', '时间结束']}
      format="YYYY-MM-DD"
      ranges={controlRange}
    />
  );
};
